<?php
/**
 * 日志记录器
 * @author solar
 * @version 1.0
 */
class Logger 
{
	private $_levelKV=array('off'=>0,'error'=>1,'warn'=>2,'info'=>3,'debug'=>4,'all'=>5);
	private $_level=4;
	private $_autoFlush=10;
	private $_logs=array();
	private $_logCount=0;
	private $currentLogger;
	private $loggerConfigs=array();
	private $instances=array();
	
	function __construct($config) {
		if(isset($config['level'])) {
			$this->_level=$this->_levelKV[$config['level']];
		}
		$this->loggerConfigs=$config['loggers'];
		$this->switchLogger($config['current']);
	}
	
	public function switchLogger($logger){
		if(!array_key_exists($logger,$this->loggerConfigs)) return false;
		if(isset($this->instances[$logger])){
			$this->currentLogger=$this->instances[$logger];
			return true;
		}
		$loggerConfig=$this->loggerConfigs[$logger];
		include PATH_CORE.'/log/'.$logger.'.php';
		$this->currentLogger = new $logger;
		$this->currentLogger->init($loggerConfig);
		$this->instances[$logger]=$this->currentLogger;
		return true;
	}
	
	public function debug($message,$category='application') {
		if($this->_level<4) return;
		$this->log($message,'debug',$category);
	}
	
	public function info($message,$category='application') {
		if($this->_level<3) return;
		$this->log($message,'info',$category);
	}
	
	public function warn($message,$category='application') {
		if($this->_level<2) return;
		$this->log($message,'warn',$category);
	}
	
	public function error($message,$category='application') {
		if($this->_level<1) return;
		$this->log($message,'error',$category);
	}
	
	private function log($message,$level,$category) {
		$this->_logs[]=array($message,$level,$category,time());
		$this->_logCount++;
		if($this->_logCount>=$this->_autoFlush) $this->flush();
	}
	
	public function flush() {
		$this->currentLogger->processLog($this->_logs);
		$this->_logs=array();
		$this->_logCount=0;
	}
	
	function __destruct() {
		$this->flush();
	}
}

?>